package cn.vendpay.com.service.impl;


import cn.vendcommon.com.entity.VideoItem;
import cn.vendpay.com.service.MinioService;
import cn.vendpay.com.service.VideoService;
import io.minio.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;

@Service
public class MinioServiceImpl implements MinioService {

    @Autowired
    private VideoService videoService;

    private final MinioClient minioClient;

    @Value("${minio.bucket}")
    private String bucketName;

    @Value("${minio.endpoint}")
    private String endpoint;

    public MinioServiceImpl(MinioClient minioClient) {
        this.minioClient = minioClient;
    }

    /**
     * 将视频上传到 minio
     * @param file 视频文件
     * @param userId 用户ID
     * @param machineId 售卖机ID
     * @return 视频URL
     * @throws Exception
     */
    @Override
    public String uploadVideo(MultipartFile file, int userId, int machineId) throws Exception {
        // 如果桶不存在则创建
        boolean exists = minioClient.bucketExists(
                BucketExistsArgs.builder().bucket(bucketName).build());
        if (!exists) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
        String originalFilename = file.getOriginalFilename();
        if (originalFilename != null && originalFilename.contains(".")) {
            originalFilename = originalFilename.substring(originalFilename.lastIndexOf(".")); // 结果：".png"
        } else {
            originalFilename = ".mp4"; // 默认扩展名
        }
        // 生成唯一文件名
        String fileName = machineId + "/" + userId + "_" + System.currentTimeMillis() + originalFilename;

        // 上传文件流
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());

        // 5. 生成预签名 URL（例如 7 天有效）
        String presignedUrl = minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(bucketName)
                        .object(fileName)
                        .expiry(60 * 60 * 24 * 7) // 有效期 7 天（单位：秒）
                        .build()
        );

        // 保存Video信息
        VideoItem videoItem = VideoItem.builder()
                .userId(userId)
                .machineId(machineId)
                .url(fileName)
                .processStatus(0) // 待处理
                .createTime(LocalDateTime.now())
                .build();

        videoService.insertVideoItem(videoItem);

        // 返回访问URL
        return presignedUrl;
    }

}
